package com.heqiang.spring.service.common;

import com.heqiang.spring.beans.factory.FactoryBean;
import com.heqiang.spring.service.TestDao;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

public class ProxyBeanFactory implements FactoryBean<TestDao> {


    @Override
    public TestDao getObject() throws Exception {
        InvocationHandler handler = (proxy, method, args) ->{
            // 添加排除方法
            if ("toString".equals(method.getName())) return this.toString();

            Map<String,String> map = new HashMap<>();
            map.put("1001", "哈哈哈");
            map.put("1002", "八杯水");
            map.put("1003", "阿毛");
            return "你被代理了"+method.getName()+":"+map.get(args[0].toString());
        };
        return (TestDao) Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{TestDao.class},handler);
    }

    @Override
    public Class<?> getObjectType() {
        return TestDao.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
